package org.vectrics.recruiter.struts.admin;

import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;

import org.apache.ecs.html.A;
import org.vectrics.SystemException;
import org.vectrics.common.html.BorderTable;
import org.vectrics.common.html.Cell;
import org.vectrics.common.html.Form;
import org.vectrics.common.html.Row;
import org.vectrics.common.pagelist.PageList;
import org.vectrics.common.util.DateUtil;
import org.vectrics.employee.Employee;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.struts.PageListTag;
import org.vectrics.user.Person;
import org.vectrics.user.PersonCommunication;
import org.vectrics.user.PersonCommunicationMethod;
import org.vectrics.user.PersonEncounter;

public class PersonEncountersTag extends PageListTag {

    private static final long serialVersionUID = -4626933176180872149L;

    private String personId = null;

    @Override
    protected String getDescription() {
        return null;
    }

    @Override
    protected String getPageListLink() {
        return "/hrs-intranet/admin/user/encounter/list.do?personId=" + getPersonId();
    }

    protected Boolean isEmployee() {
        String userId = getRequest().getParameter("userId");

        if (userId == null || userId.trim().length() == 0) {
            userId = (String) getRequest().getAttribute("userId");
        }
        if (userId == null || userId.trim().length() == 0) {
            userId = (String) getRequest().getSession().getAttribute("userId");
        }
        if (userId == null || userId.trim().length() == 0) {
            userId = getRequest().getParameter("id");
        }
        if (userId == null || userId.trim().length() == 0) {
            userId = getRequest().getParameter("personId");
        }
        if (userId == null || userId.trim().length() == 0) {
            userId = (String) getRequest().getAttribute("personId");
        }
        if (userId != null && userId.equals("current")) {
            userId = ThreadProperties.getPerson().getId().toString();
        }
        String personId = userId;
        if (userId == null || userId.trim().length() == 0)
            throw new RuntimeException("User ID is blank or null");

        String companyId = ThreadProperties.getDomain().getPrimaryCompany().getId().toString();

        // Busco el empleado de la compania.
        Employee employee = RecruitServiceLocator.getCompanyService().findEmployee(new Long(personId),
                new Long(companyId));
        return employee != null;
    }

    @Override
    protected void showList(final String description, final Cell mainCell, final List elements, final Form form) {
        BorderTable mainTable = new BorderTable();
        mainTable.setWidth("90%");
        mainCell.addElement(mainTable);

        Row hdrRow = mainTable.addRow();
        hdrRow.setDefaultCellFontClass("tableHdrFont");
        hdrRow.setDefaultBgImage(getContextPath() + "/site-graphics/tbl_hdr.gif");

        Cell hdrCell = null;

        hdrCell = hdrRow.addCell();
        hdrCell.addText(this.getPhrase("prompt.encounter.start.datetime"));

        hdrCell = hdrRow.addCell();
        hdrCell.addText(this.getPhrase("prompt.encounter.end.datetime"));

        hdrCell = hdrRow.addCell();
        hdrCell.addText(this.getPhrase("prompt.encounter.description"));

        hdrCell = hdrRow.addCell();
        hdrCell.addText(this.getPhrase("prompt.encounter.from.person"));

        hdrCell = hdrRow.addCell();
        hdrCell.addText(this.getPhrase("prompt.encounter.to.person"));

        hdrCell = hdrRow.addCell();
        hdrCell.addText(this.getPhrase("prompt.encounter.status"));

        if (isEmployee() && hasPermission("manage_employees_items")) {
            hdrCell = hdrRow.addCell();
            hdrCell.addText(" &nbsp; ");
            hdrCell = hdrRow.addCell();
            hdrCell.addText(" &nbsp; ");
        } else {
            if (!isEmployee() && hasPermission("manage_candidate_items")) {
                hdrCell = hdrRow.addCell();
                hdrCell.addText(" &nbsp; ");
                hdrCell = hdrRow.addCell();
                hdrCell.addText(" &nbsp; ");
            }
        }
        Iterator iter = elements.iterator();
        while (iter.hasNext()) {
            PersonEncounter encounter = (PersonEncounter) iter.next();
            Row row = mainTable.addRow();
            row.setDefaultCellFontClass("subFont");

            Cell cell = row.addCell();
            if (encounter.getDateStart() != null) {
                // SimpleDateFormat dateFormat =
                // CoreServiceLocator.getDateFormat().getDateFormatRoundToMinute(this.getLocale());
                // cell.addText(dateFormat.format(encounter.getDateStart()));
                cell.addText(DateUtil.getFechaHoraFormateada(encounter.getDateStart()));
            }

            cell = row.addCell();
            if (encounter.getDateEnd() != null) {
                SimpleDateFormat dateFormat = CoreServiceLocator.getDateFormat().getDateFormatForHourAndMinute(
                        getLocale());
                cell.addText(dateFormat.format(encounter.getDateEnd()));
            }

            cell = row.addCell();
            String encounterDescription = "";
            if (encounter instanceof PersonCommunication) {
                PersonCommunication communication = (PersonCommunication) encounter;
                PersonCommunicationMethod method = communication.getMethod();
                if (communication.getMethod() == null) {
                    encounterDescription = "";
                } else {
                    communication.getMethod();
                    encounterDescription = CoreServiceLocator.getPhraseProvider().getMessage(
                            method.getPersonCommunicationMethodType().getDescriptionCode(), getLocale());
                }
            } else {
                encounterDescription = encounter.getDescription();
            }
            A encounterLink = new A();
            encounterLink.setClass("subLink");
            encounterLink.addElement(encounterDescription);
            encounterLink.setHref("/hrs-intranet/admin/user/encounter/viewPhoneCall.do?personCommunicationId="
                    + encounter.getId().toString() + "&personId=" + getPersonId());
            cell.addElement(encounterLink);

            cell = row.addCell();
            if (encounter.getLeadPerson() != null) {
                cell.addText(encounter.getLeadPerson().getFullName());
            } else {
                cell.addText("");
            }

            cell = row.addCell();
            if (encounter.getPerson() != null) {
                cell.addText(encounter.getPerson().getFullName());
            } else {
                cell.addText("");
            }

            cell = row.addCell();
            cell.addText(encounter.getEncounterStatus().getName());

            if (isEmployee() && hasPermission("manage_employees_items")) {
                addEditDeleteCells(encounter, row);
            } else {
                if (!isEmployee() && hasPermission("manage_candidate_items")) {
                    addEditDeleteCells(encounter, row);
                }
            }
        }
    }

    private void addEditDeleteCells(final PersonEncounter encounter, final Row row) {
        Cell cell;
        cell = row.addCell();
        if (encounter instanceof PersonCommunication) {
            A link = new A();
            link.setClass("subLink");
            link.addElement(this.getPhrase("prompt.encounter.edit"));
            link.setHref("/hrs-intranet/admin/user/encounter/editPhoneCall.do?personCommunicationId="
                    + encounter.getId().toString());
            cell.addElement(link);
        }
        cell = row.addCell();
        if (encounter instanceof PersonCommunication) {
            A deleteLink = new A();
            deleteLink.setClass("subLink");
            deleteLink.addElement(this.getPhrase("prompt.encounter.remove"));
            String href = "/hrs-intranet/admin/user/encounter/deletePhoneCall.do?personCommunicationId="
                    + encounter.getId().toString();
            href += "&personId=" + getPersonId();
            deleteLink.setHref(href);
            deleteLink.setOnClick(" if (confirm('" + this.getPhrase("prompt.encounter.confirm.delete") + "'))"
                    + "       return true;" + "  else return false;");
            cell.addElement(deleteLink);
        }
    }

    /**
     * Make page list for this tag.
     */
    @Override
    protected PageList createPageList() {
        Person person = CoreServiceLocator.getPersonService().findPersonById(new Long(getPersonId()));
        if (person == null)
            throw new SystemException("Could not find person for id: " + getPersonId());
        PersonEncountersPageList pageList = new PersonEncountersPageList(person);

        return pageList;
    }

    public String getPersonId() {
        return personId;
    }

    public void setPersonId(final String personId) {
        this.personId = personId;
    }

}
